package com.jijidom.product.service;

import com.jijidom.common.DecreaseStockInput;
import com.jijidom.product.dataobject.ProductInfo;
import com.jijidom.product.enums.ProductsStatusEnum;
import com.jijidom.product.enums.ResultEnum;
import com.jijidom.product.exception.ProductException;
import com.jijidom.product.repository.ProductInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @ClassName
 * @Description TODO
 * @Author JinTao
 * @Date 2018/9/6 11:28
 * @Version 1.0
 **/
@Service
public class ProductService {

    @Autowired
    private ProductInfoRepository productInfoRepository;

    public List<ProductInfo> findUpAll(){
        return productInfoRepository.findByProductStatus(ProductsStatusEnum.UP.getCode());
    }

    public List<ProductInfo> findByProductIdIn(List<String> productIdList){
        return productInfoRepository.findByProductIdIn(productIdList);
    }

    /**
     * 扣库存
     * @param carDTOList
     */
    public void decreaseStock(List<DecreaseStockInput> carDTOList){
        for (DecreaseStockInput carDTO: carDTOList){
            Optional<ProductInfo> productInfoOptional = productInfoRepository.findById(carDTO.getProductId());
            if (!productInfoOptional.isPresent()){
                throw new ProductException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            ProductInfo productInfo = productInfoOptional.get();
            Integer result = productInfo.getProductStock() - carDTO.getProductQuantity();
            if (result < 0){
                throw  new ProductException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(result);
            productInfoRepository.save(productInfo);
        }
    }
}
